﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AsyncProgressNotify
{
	/// <summary>
	/// Interaction logic for MyTaskProgress.xaml
	/// </summary>
	public partial class MyTaskProgress : UserControl
	{
		public MyTaskProgress()
		{
			InitializeComponent();
		}

		private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
		{
			MyTask context = e.NewValue as MyTask;
			if (context != null)
			{
				// register event to check for value changes in future
				DynamicProperties.Extender.Global.RegisterOnChanged(context, PropDef.dpMyTaskProgress, MyTaskProgress_OnChanged);

				// check current value
				double progress;
				PropDef.dpMyTaskProgress.TryGet(context, out progress);
				SetProgress(progress);
			}
		}

		void MyTaskProgress_OnChanged(MyTask target, DynamicProperties.DynamicPropertyChangedParams<MyTask, double> args)
		{
			this.Dispatcher.BeginInvoke(new Action(() =>
			{
				SetProgress(args.NewValue);
				
			}), null);
		}

		private void SetProgress(double progress)
		{
			if (progress < 1)
			{
				// change progress
				progressBar.Value = progress;
			}
			else
			{
				// hide progress bar
				allDone.Visibility = System.Windows.Visibility.Visible;
				progressBar.Visibility = System.Windows.Visibility.Hidden;
			}
		}
	}
}
